#!/bin/bash
#
# Copyright (c) 2023, 2025 Eurotech and/or its affiliates and others
#
# This program and the accompanying materials are made
# available under the terms of the Eclipse Public License 2.0
# which is available at https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
#
# Contributors:
#  Eurotech
#

INSTALL_DIR=/opt/eclipse
WD_TMP_FILE=/tmp/watchdog
REFRESH_TIME=5
TIMEOUT_TIME=300
TIMESTAMP=$(date +%Y%m%d%H%M)
LOG=/tmp/kura_uninstall_${TIMESTAMP}.log

##############################################
# UTILITY FUNCTIONS
##############################################
# Run preRemove function and start watchdog if needed
function runPreRemove {
    if [ -f "${WD_TMP_FILE}" ]; then
        WATCHDOG_DEVICE=`cat ${WD_TMP_FILE}`
        preRemove &
        PID=$!
        START=$(date +%s)
        
        while [ -d "/proc/$PID" ]; do
            echo w > ${WATCHDOG_DEVICE}
            DELTA=$(($(date +%s) - $START))
            if [ "$DELTA" -ge "$TIMEOUT_TIME" ]; then
                echo "The installation process is not responding. It'll be stopped."
                kill -9 $PID >> /dev/null 2>&1
            fi
            sleep $REFRESH_TIME
        done
        stopWatchdog
    else
        preRemove &
        PID=$!
        START=$(date +%s)
        
        while [ -d "/proc/$PID" ]; do
            DELTA=$(($(date +%s) - $START))
            if [ "$DELTA" -ge "$TIMEOUT_TIME" ]; then
                echo "The installation process is not responding. It'll be stopped."
                kill -9 $PID >> /dev/null 2>&1
            fi
            sleep $REFRESH_TIME
        done
    fi
}

# Deactivate watchdog device if possible
function stopWatchdog {
    if [ -n "${WATCHDOG_DEVICE}" ]; then
        echo V > ${WATCHDOG_DEVICE}
    fi
}

function restore_systemd_watchdog() {
    file_to_restore=""

    if [ -f /usr/lib/systemd/system.conf.d/zz-kura-disable-watchdog.conf ]; then
        file_to_restore="/usr/lib/systemd/system.conf.d/zz-kura-disable-watchdog.conf"
    fi
    if [ -f /usr/local/lib/systemd/system.conf.d/zz-kura-disable-watchdog.conf ]; then
        file_to_restore="/usr/local/lib/systemd/system.conf.d/zz-kura-disable-watchdog.conf"
    fi
    if [ -f /etc/systemd/system.conf.d/zz-kura-disable-watchdog.conf ]; then
        file_to_restore="/etc/systemd/system.conf.d/zz-kura-disable-watchdog.conf"
    fi

    if [ ! -z "${file_to_restore}" ]; then
        echo "Restoring systemd watchdog configuration: removing ${file_to_restore}"
        rm "${file_to_restore}"
        systemctl daemon-reload
    fi
}

function restore_backup_files {
    SUFFIX="${1}"

    shift

    for file in "${@}"
    do
        if [ -f "${file}" ] && expr "${file}" : ".*[.]${SUFFIX}$" > /dev/null; then
            mv "${file}" "${file%."${SUFFIX}"}"
        fi
    done
}

# Pre-remove script
function preRemove {
    #Remove INIT scripts
    if [ -f /etc/init.d/kura ] ; then
        rm /etc/init.d/kura
        update-rc.d kura remove
    fi
    if [ -f /lib/systemd/system/kura.service ] ; then
        systemctl disable kura
        rm /lib/systemd/system/kura.service
    fi

    rm -f  /var/log/kura*.log
    rm -f  /var/log/kura*.gz
    rm -rf /tmp/.kura
    rm -rf /tmp/kura

    if [ -d "${INSTALL_DIR}/kura" ] ; then
      ${INSTALL_DIR}/kura/.data/manage_kura_users.sh -u
      PARENT=`readlink -f ${INSTALL_DIR}/kura`
      rm -rf ${INSTALL_DIR}/kura
      rm -rf $PARENT
    fi

    restore_systemd_watchdog
}
##############################################
# END UTILITY FUNCTIONS
##############################################

##############################################
# PRE-REMOVE SCRIPT
##############################################

# Fail if the first argument is 'upgrade' or 'failed-upgrade'
if [ "$1" == "upgrade" ]; then
    echo ""
    echo "#####################################################################"
    echo "#                                                                   #"
    echo "#  ERROR: KURA upgrade is NOT supported!                            #"
    echo "#  Please uninstall the existing version before upgrading.          #"
    echo "#                                                                   #"
    echo "#  To prevent accidental upgrades, you can hold this package with:  #"
    echo "#      sudo apt-mark hold kura                                      #"
    echo "#                                                                   #"
    echo "#####################################################################"
    echo ""
    exit 1
fi

if [ "$1" == "failed-upgrade" ]; then
    echo "This package cannot be upgraded. Please uninstall the existing version before installing a new one."
    exit 1
fi

echo ""
echo "Uninstalling KURA..."

PIDS=`pgrep java`

#Kill JVM and monit for installation
if [ -f "/var/run/kura.pid" ] ; then
  KURA_PID=`cat /var/run/kura.pid`

  for pid in "${PIDS[@]}"
  do
    if [ "$KURA_PID" == "$pid" ] ; then
      `kill $pid` >> "$LOG" 2>&1
    fi
  done
fi

runPreRemove >> "$LOG" 2>&1

mkdir -p /opt/eclipse/kura/log/
mv "$LOG" /opt/eclipse/kura/log/

echo ""
echo "Uninstalling KURA... Done!"
##############################################
# END PRE-REMOVE SCRIPT
##############################################
